package io.renren.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import io.renren.entity.EmpBaseinfoEntity;
import io.renren.entity.EmpInfoModifyEntity;
import io.renren.entity.SysUserEntity;
import io.renren.entity.VO.EmpBaseinfoEntityVO;
import io.renren.entity.VO.EmpBaseinfoParams;
import io.renren.service.DictUtilsService;
import io.renren.service.EmpBaseinfoService;
import io.renren.utils.*;
import io.renren.utils.excel.ExportExcel;
import io.renren.utils.excel.ImportExcel;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.io.File;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * @author chenshun
 * @email sunlightcs@gmail.com
 * @date 2017-06-15 20:58:29
 */
@RestController
@RequestMapping("empbaseinfo")
public class EmpBaseinfoController extends AbstractController {

    @Autowired
    private EmpBaseinfoService empBaseinfoService;
    @Autowired
    private DictUtilsService dictUtilsService;
    /*@Autowired
	private HttpServletRequest request;
	 @Autowired
	 private HttpServletResponse response;*/

    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("empbaseinfo:list")
    public R list(@RequestParam Map<String, Object> params) {

        //查询列表数据
        QueryAuthority query = new QueryAuthority(params);
        List<EmpBaseinfoEntityVO> empBaseinfoList = empBaseinfoService.queryListVO(query);
        //List<EmpBaseinfoEntity> empBaseinfoList = empBaseinfoService.queryList(query);

        int total = empBaseinfoService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(empBaseinfoList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("empbaseinfo:info")
    public R info(@PathVariable("id") Integer id, HttpServletRequest request) {
        //EmpBaseinfoEntity empBaseinfo = empBaseinfoService.queryObject(id);
        EmpBaseinfoParams empBaseinfo = empBaseinfoService.queryObjectVO(id.toString());
        //SysOssEntity ossEntity = sysOssService.queryObject(Long.valueOf(empBaseinfo.getFileId()));
        String imaurl = "";
        //if(ossEntity!=null){
        //提取后缀\
		if(!StringUtils.isBlank(empBaseinfo.getIdcardpath())){
            String postfixName = empBaseinfo.getIdcardpath().substring(empBaseinfo.getIdcardpath().lastIndexOf("\\"));//ossEntity.getUrl().substring(ossEntity.getUrl().lastIndexOf("\\"));
            String url = request.getRequestURL().toString();
            String[] str = url.split("/");
            imaurl = str[0] + "//" + str[2] + "/upload/" + postfixName.substring(1, postfixName.length());
        }
        //}
        return R.ok().put("empBaseinfo", empBaseinfo).put("imaurl", imaurl);
    }

    /**
     * 保存
     */
    @RequestMapping("/save")
    @RequiresPermissions("empbaseinfo:save")
    public R save(@RequestBody EmpBaseinfoParams empBaseinfo) {
        SysUserEntity user = (SysUserEntity) ShiroUtils.getSubject().getSession().getAttribute("user");
        empBaseinfo.setCreateperson(user.getUsername());
        empBaseinfo.setCreatetime(new Date());
        empBaseinfoService.save(empBaseinfo);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    @RequiresPermissions("empbaseinfo:update")
    public R update(@RequestBody EmpBaseinfoParams empBaseinfo) {
        empBaseinfoService.update(empBaseinfo);

        return R.ok();
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    @RequiresPermissions("empbaseinfo:delete")
    public R delete(@RequestBody Integer[] ids) {
        empBaseinfoService.deleteBatch(ids);

        return R.ok();
    }

    /**
     * 添加到黑名单
     */
    @RequestMapping("/updatestatus")
    @RequiresPermissions("empbaseinfo:update")
    public R updateStatus(@RequestBody JSONObject params) {
        empBaseinfoService.updateStatus(params);

        return R.ok();
    }

    /**
     * @return
     */
    @RequestMapping("/getListinfo")
    @RequiresPermissions("empbaseinfo:select")
    public R getListinfo() {
        Map<String, Object> map = empBaseinfoService.getListinfo();
        return R.ok(map);
    }

    //插入派遣信息
    @RequestMapping("/insertdispatch")
    public R insertDispatch(@RequestBody JSONObject params) {
        SysUserEntity user = getUser();
        empBaseinfoService.insertDispatch(params, user);
        return R.ok();
    }

    //插入面试数据
    @RequestMapping("/insertinterview")
    public R insertInterview(@RequestBody JSONObject params) {
        SysUserEntity user = getUser();
        empBaseinfoService.insertInterview(params, user);
        return R.ok();
    }

    /**
     * 上传身份证照片
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/uploadCard", method = RequestMethod.POST, headers = {"Content-Type=multipart/form-data"})
    public R test(@RequestBody MultipartFile file, HttpServletRequest request) {

        String filePath = "";
        // 判断文件是否为空
        if (!file.isEmpty()) {
            if (file.getSize() > 10240000) {
                throw new RRException("上传失败：文件大小不能超过10M");
            }
            try {
                //提取后缀
                String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

                // 文件保存路径
                filePath = request.getSession().getServletContext().getRealPath("/") + "upload\\" + getUser().getUsername() + "_"
                        + DateUtils.format(new Date(), "yyyyMMddHHmmss") + postfix;
                File saveDir = new File(filePath);

                //判断目标文件所在的目录是否存在
                if (!saveDir.getParentFile().exists()) {
                    //如果目标文件所在的目录不存在，则创建父目录
                    saveDir.getParentFile().mkdirs();
                }
                // 转存文件
                file.transferTo(saveDir);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            throw new RRException("上传失败:请添加上传文件！");
        }

        //保存文件信息
//		SysOssEntity ossEntity = new SysOssEntity();
//		ossEntity.setUrl(filePath);
//		ossEntity.setCreateDate(new Date());
//		ossEntity.setFileName(file.getOriginalFilename());
//		ossEntity.setUrlType("0");
        //sysOssService.save(ossEntity);

        System.out.println("filePath:" + filePath);
        return R.ok().put("url", filePath);//.put("fileId",ossEntity.getId());

//		System.out.println(file);
//		return R.ok();
    }

    /**
     * 导出excel文件
     */
    @RequiresPermissions("empbaseinfo:list")
    @RequestMapping(value = "/list/export", method = RequestMethod.GET)
    public String exportFile(HttpServletRequest request, HttpServletResponse response/*, @RequestParam Map<String, Object> params*/) {
        try {
            String op =request.getParameter("op");
            List<EmpBaseinfoEntity> list =null;
            if("export".equals(op)){//导出数据
                //list = empBaseinfoService.queryListVO();
            }else if("download".equals(op)){//下载模板
                list = Lists.newArrayList();
            }
            String fileName = "员工求职信息" + DateUtils.format(new Date(),"yyyyMMddHHmmss") + ".xlsx";
            new ExportExcel("员工求职信息", EmpBaseinfoEntity.class).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            //throw new RRException("导出求职者信息管理记录失败！失败信息：" + e.getMessage());
        }
        System.out.println("out!!!");
        return "redirect:empbaseinfo/list";
    }
    /**
     * 导入Excel数据

     */
    @RequiresPermissions("empbaseinfo:import")
    @RequestMapping(value ="/import", method = RequestMethod.POST,headers={"Content-Type=multipart/form-data"})
    public R importFile(@RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                String filename = file.getOriginalFilename();
                //提取后缀
                String postfix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                if(!".xls".equals(postfix)&&!".xlsx".equals(postfix)){
                    throw new RRException("文件格式不正确");
                }
                int successNum = 0;
                int failureNum = 0;
                StringBuilder failureMsg = new StringBuilder();
                ImportExcel ei = new ImportExcel(file, 1, 0);
                List<EmpBaseinfoEntity> list = ei.getDataList(EmpBaseinfoEntity.class);
                for (EmpBaseinfoEntity empnum : list){
                    try{
                        empnum.setStatus("0");
                        empnum.setIswork("0");
                        empnum.setFreeFlag("0");
                        empnum.setDelFlag("0");
                        String sex = dictUtilsService.getValueByLabel(empnum.getSex());
                        if(sex!=null){
                            empnum.setSex(sex);
                        }
                        String nation = dictUtilsService.getValueByLabel(empnum.getNation());
                        if(nation!=null){
                            empnum.setNation(nation);
                        }
                        String polstatus = dictUtilsService.getValueByLabel(empnum.getPolstatus());
                        if(polstatus!=null){
                            empnum.setPolstatus(polstatus);
                        }
                        String married = dictUtilsService.getValueByLabel(empnum.getMarried());
                        if(married!=null){
                            empnum.setMarried(married);
                        }
                        String education = dictUtilsService.getValueByLabel(empnum.getEducation());
                        if(education!=null){
                            empnum.setEducation(education);
                        }
                        String post = dictUtilsService.getValueByLabel(empnum.getJob());
                        if(post!=null){
                            empnum.setJob(post);
                        }
                        empBaseinfoService.saveEmpBaseInfo(empnum);
                        successNum++;
                    }catch(ConstraintViolationException ex){
                        failureNum++;
                    }catch (Exception ex) {
                        failureNum++;
                    }
                }
                if (failureNum>0){
                    failureMsg.insert(0, "，失败 "+failureNum+" 条预警记录。");
                }
                throw new RRException("已成功导入 "+successNum+" 条 求职人员编号自动生成记录"+failureMsg);
            }else{
                throw new RRException("上传失败:请添加上传文件！");
            }
        } catch (RRException e) {
            throw e;
        }catch (Exception e) {
            //throw new RRException("导入 求职人员编号自动生成失败！失败信息："+e.getMessage());
        }
        return R.ok();
    }
}
